#!/usr/bin/env bash
BUILD_START_TIME=$(date +%s)

# Auto-log everything to timestamped file
LOG_FILE="build_$(date +%Y%m%d_%H%M%S).log"
exec > >(tee -a "$LOG_FILE") 2>&1
echo "📝 Logging to: $LOG_FILE"

PROJECT_ROOT="$(cd "$(dirname "$0")" && pwd)"
PARENT_DIR="$(cd "$PROJECT_ROOT/.." && pwd)"
PACKAGE_CACHE_DIR="$PARENT_DIR/package_cache"
GENERATED="$PARENT_DIR/_generated"
BUILD_DIR="$PARENT_DIR/build"
ISO_DIR="$GENERATED/iso"
WORK_DIR="$GENERATED/work"
ISO_ROOT="$GENERATED/iso-root"
SQUASHFS_ROOT="$WORK_DIR/squashfs-root"
OUTPUT_DIR="$BUILD_DIR/output"

# Skip slow netselect-apt, use bulletproof mirrors
DEBIAN_MIRROR="http://deb.debian.org/debian"  # Auto-mirrors globally
SECURITY_MIRROR="http://deb.debian.org/debian-security"

echo "🚀 Using reliable mirrors: $DEBIAN_MIRROR"

set -e # Exit if any script crashes

echo ""
echo "╔════════════════════════════════════════╗"
echo "║   FurryOS Gen2.1_v2 Build System       ║"
echo "╚════════════════════════════════════════╝"
echo ""

# [Phase 0] Smart Clean Menu
echo "[Phase 0] Build Cleanup Menu..."
echo "  C = Clean everything"
echo "  K = Keep everything (incremental)"
echo "  D = Clean but keep Debian ISO"
read -p "C/K/D [C]: " -n 1 -r BUILD_MODE
echo ""

case ${BUILD_MODE,,} in
    k ) echo "➡️  Incremental build..."; ;;
    d )
        echo "💾 Clean + Keep Debian ISO..."
        sudo umount -l "$SQUASHFS_ROOT" "$ISO_ROOT" 2>/dev/null || true
        sudo rm -rf "$WORK_DIR/squashfs-root" "$ISO_ROOT"
        echo " ✓ ISO preserved";;
    *|"c" )
        echo "🔥 Full clean..."
        sudo umount -l "$SQUASHFS_ROOT" "$ISO_ROOT" 2>/dev/null || true
        sudo rm -rf "$BUILD_DIR" "$GENERATED" "$WORK_DIR" "$ISO_ROOT" "$SQUASHFS_ROOT"
        rm -f "$PROJECT_ROOT"/*.iso
        echo " ✓ Clean!";;
esac

# Ensure ALL working directories exist (bulletproof)
# Bulletproof: Create ALL dirs needed anywhere in script
echo "[Phase 0.1] Creating ALL working directories..."
mkdir -p "$BUILD_DIR/output" \
  "$PACKAGE_CACHE_DIR" \
  "$GENERATED/iso" \
  "$GENERATED/work" \
  "$ISO_ROOT" \
  "$SQUASHFS_ROOT" \
  "$SQUASHFS_ROOT/tmp/packages" \
  "$SQUASHFS_ROOT/usr/share/furryos" \
  "$SQUASHFS_ROOT/usr/share/backgrounds/furryos" \
  "$SQUASHFS_ROOT/usr/share/sounds/furryos" \
  "$SQUASHFS_ROOT/etc/skel/.config/autostart" \
  "$SQUASHFS_ROOT/usr/share/applications" \
  "$SQUASHFS_ROOT/boot/grub" \
  "$SQUASHFS_ROOT/etc/dconf/db/local.d" || true

echo "  ✓ ALL directories ready (core + subdirs + chroot targets)"

echo ""

# Auto-calculate 75% of available RAM for mksquashfs (YouTube-safe)
if command -v free >/dev/null 2>&1; then
    # Get total RAM in GB
    TOTAL_RAM_GB=$(free --giga | awk '/^Mem:/ {print int($2)}')

    # Get available RAM using MemAvailable (accurate)
    AVAILABLE_RAM_GB=$(free --mega | awk '/^Mem:/ {print int($7/1024)}')

    SQUASHFS_MEM_GB=$((AVAILABLE_RAM_GB * 75 / 100))

    # Bounds check
    if [ "$SQUASHFS_MEM_GB" -lt 2 ]; then
        SQUASHFS_MEM_GB=2
    elif [ "$SQUASHFS_MEM_GB" -gt 20 ]; then
        SQUASHFS_MEM_GB=20  # Max 20G even on 32GB systems
    fi

    SQUASHFS_MEM="${SQUASHFS_MEM_GB}G"

    # CPUs: Conservative for heat/noise
    SQUASHFS_CPUS=$((TOTAL_RAM_GB / 6))  # 1 CPU per 6GB (quieter)
    if [ "$SQUASHFS_CPUS" -gt 12 ]; then
        SQUASHFS_CPUS=12
    elif [ "$SQUASHFS_CPUS" -lt 2 ]; then
        SQUASHFS_CPUS=2
    fi

    echo "📊 ${TOTAL_RAM_GB}GB total, ${AVAILABLE_RAM_GB}GB avail → ${SQUASHFS_MEM} (75%) RAM, ${SQUASHFS_CPUS} CPUs"
else
    SQUASHFS_MEM="4G"
    SQUASHFS_CPUS=2
    echo "📊 Using YouTube-safe defaults: 4G RAM, 2 CPUs"
fi

# Track build time and suppress xattr warnings
BUILD_START_TIME=$(date +%s)
exec 2> >(grep -v "Unrecognised xattr" >&2)

# ═══════════════════════════════════════════════════════════════════
# FurryOS Gen2.1_v2 Enhanced Build Script
# Features: Mode-based bundle installation, Plymouth splash, themes
# ═══════════════════════════════════════════════════════════════════

echo "══════════════════════════════════════════════════════════════"
echo "          FurryOS Gen2.1_v2 Enhanced Build System"
echo "══════════════════════════════════════════════════════════════"
echo "Project root: $PROJECT_ROOT"
cd "$PROJECT_ROOT"

# ═══════════════════════════════════════════════════════════════════
# Python Environment Setup
# ═══════════════════════════════════════════════════════════════════

if ! command -v python3 &>/dev/null; then
    echo "ERROR: python3 not found"
    exit 1
fi

echo "Installing/updating Python requirements (pyyaml, rich, requests)..."

# Prefer clean user install first (best for your host system)
if pip install --user --upgrade pyyaml rich requests; then
    echo "✓ Python requirements installed (user mode - clean!)"
else
    # Fallback: only if user install fails (rare in build envs), use root but silence the warning
    echo "User install unavailable, using root mode with warning suppressed..."
    pip install --root-user-action=ignore --upgrade pyyaml rich requests
    echo "✓ Python requirements installed (root mode, no warnings)"
fi

# ═══════════════════════════════════════════════════════════════════
# Phase 1-3: Validation
# ═══════════════════════════════════════════════════════════════════

echo ""
echo "[Phase 1] Validating GENOME.yaml"
if [ -f "GENOME_Gen2.1_v2_Enhanced.yaml" ]; then
    ln -sf GENOME_Gen2.1_v2_Enhanced.yaml GENOME.yaml
    echo "  ✓ Using enhanced GENOME.yaml"
fi

echo ""
echo "[Phase 2] Checking assets"
python3 << 'ASSETCHECK'
from pathlib import Path
import yaml

root = Path.cwd()
genome_file = root / "GENOME.yaml"

if genome_file.exists():
    genome = yaml.safe_load(genome_file.open())
    assets = genome.get("assets", {})
    asset_root = root / assets.get("root", "payload/assets")

    required = assets.get("required", {})
    for name, path in required.items():
        full_path = asset_root / path
        if full_path.exists():
            print(f"  ✓ {name}: {path}")
        else:
            print(f"  ⚠ MISSING {name}: {path}")
else:
    print("  ⚠ GENOME.yaml not found")
ASSETCHECK

# ═══════════════════════════════════════════════════════════════════
# Phase 3-5: ISO Download and Extraction
# ═══════════════════════════════════════════════════════════════════

echo "[Phase 3] Quick mirror setup (no DNS hassle)..."

# Minimal reliable sources.list - NO netselect-apt, NO resolv.conf mess
cat > "$SQUASHFS_ROOT/etc/apt/sources.list" << 'EOF'
# FurryOS Gen2.1 - Reliable global mirrors
deb http://deb.debian.org/debian trixie main contrib non-free non-free-firmware
deb http://deb.debian.org/debian trixie-updates main contrib non-free non-free-firmware
deb http://deb.debian.org/debian-security trixie-security main contrib non-free non-free-firmware
deb http://ftp.us.debian.org/debian trixie-backports main contrib non-free non-free-firmware
EOF

# Skip chroot apt test - let Phase 5.5 handle it naturally
echo " ✓ Mirrors ready (deb.debian.org auto-optimizes)"

echo "  ✓ Phase 3.0 complete"

echo ""
echo "[Phase 3.1] Ensuring Debian base ISO"

echo
echo "ℹ️ This step may appear idle for several minutes."
echo "   The Debian Live ISO is being downloaded and verified."
echo "   Please be patient — the build is still running."
echo "   (Once downloaded, future builds will skip this step.)"
echo

mkdir -p "$ISO_DIR"
ISO_FILE="$ISO_DIR/debian-live-mate-amd64.iso"
ISO_URL="https://cdimage.debian.org/debian-cd/current-live/amd64/iso-hybrid/debian-live-13.2.0-amd64-mate.iso"

if [ -f "$ISO_FILE" ]; then
    SIZE=$(stat -c%s "$ISO_FILE" 2>/dev/null || stat -f%z "$ISO_FILE" 2>/dev/null)
    if [ "$SIZE" -lt 100000000 ]; then
        echo "  Existing ISO invalid, re-downloading..."
        rm -f "$ISO_FILE"
    else
        echo "  ✓ ISO present and valid"
    fi
fi

if [ ! -f "$ISO_FILE" ]; then
    echo "  Downloading Debian Live MATE ISO (this may take time)..."
    curl -L "$ISO_URL" -o "$ISO_FILE"
fi

echo ""
echo "[Phase 4] Extracting ISO..."
mkdir -p "$ISO_ROOT" "$SQUASHFS_ROOT"

# Bulletproof extraction
if [ -f "$ISO_FILE" ]; then
    sudo mount -o loop "$ISO_FILE" /mnt -o ro || true
    sudo rsync -aHAX /mnt/ "$ISO_ROOT/"
    sudo umount /mnt || true

    if [ -f "$ISO_ROOT/live/filesystem.squashfs" ]; then
        sudo unsquashfs -d "$SQUASHFS_ROOT" "$ISO_ROOT/live/filesystem.squashfs"
        echo " ✓ Extracted!"
    else
        echo "❌ No filesystem.squashfs found!"
        exit 1
    fi
else
    echo "❌ ISO missing: $ISO_FILE"
    exit 1
fi

# ═══════════════════════════════════════════════════════════════════
# Phase 5: Asset Installation
# ═══════════════════════════════════════════════════════════════════

echo ""
echo "[Phase 5] Installing FurryOS Assets"
PAYLOAD_DIR="$PROJECT_ROOT/payload"
FURRYOS_SHARE="$SQUASHFS_ROOT/usr/share/furryos"

mkdir -p "$FURRYOS_SHARE"

# Copy ALL assets to central location
if [ -d "$PAYLOAD_DIR/assets" ]; then
    echo "  Copying assets to /usr/share/furryos..."
    cp -rv "$PAYLOAD_DIR/assets"/* "$FURRYOS_SHARE"/ 2>/dev/null || true

    # Link to standard system locations
    if [ -d "$FURRYOS_SHARE/wallpapers" ]; then
        mkdir -p "$SQUASHFS_ROOT/usr/share/backgrounds/furryos"
        cp "$FURRYOS_SHARE/wallpapers"/* "$SQUASHFS_ROOT/usr/share/backgrounds/furryos/" 2>/dev/null || true
        echo "    ✓ Wallpapers installed"
    fi

    if [ -d "$FURRYOS_SHARE/sounds" ]; then
        mkdir -p "$SQUASHFS_ROOT/usr/share/sounds/furryos"
        cp "$FURRYOS_SHARE/sounds"/* "$SQUASHFS_ROOT/usr/share/sounds/furryos/" 2>/dev/null || true
        echo "    ✓ Sounds installed"
    fi

    if [ -d "$FURRYOS_SHARE/desktop" ]; then
        echo "    ✓ Desktop files ready"
    fi
else
    echo "  ⚠ No assets found in $PAYLOAD_DIR/assets"
fi

echo ""
echo ""
echo "[Phase 5.5] Installing packages (auto-resolves deps)..."

sudo chroot "$SQUASHFS_ROOT" bash -c "
    export DEBIAN_FRONTEND=noninteractive
    apt-get update -qq
    apt-get install -y -qq vlc geeqie ffmpeg file-roller p7zip-full p7zip-rar unrar pdfarranger mate-utils
    apt-get clean
"

echo " ✓ VLC/Geeqie/ffmpeg/etc installed perfectly"

# ═══════════════════════════════════════════════════════════════════
# Phase 6: Splash Screen Image
# ═══════════════════════════════════════════════════════════════════

echo ""
echo ""
echo "[Phase 6] Configuring Boot Splash (GRUB Only - No Plymouth)"
# Removed TITLE line
mkdir -p "$SQUASHFS_ROOT/boot/grub"

# Copy splash image - FIXED VARIABLE NAME
if [ -f "$FURRYOS_SHARE/splash/splash.png" ]; then
  cp "$FURRYOS_SHARE/splash/splash.png" "$SQUASHFS_ROOT/boot/grub/splash.png"
  echo " ✓ Splash image installed"
else
  echo "  ⚠ No splash.png found in $FURRYOS_SHARE/splash/"
fi

# Configure GRUB
if [ ! -f "$SQUASHFS_ROOT/etc/default/grub" ]; then
  echo "  ⚠ GRUB config not found, creating default..."
  cat > "$SQUASHFS_ROOT/etc/default/grub" << 'GRUBDEFAULT'
GRUB_DEFAULT=0
GRUB_TIMEOUT=5
GRUB_DISTRIBUTOR="FurryOS"
GRUB_CMDLINE_LINUX_DEFAULT="plymouth.enable=0"
GRUB_CMDLINE_LINUX=""
GRUBDEFAULT
fi

# Add FurryOS splash configuration
cat >> "$SQUASHFS_ROOT/etc/default/grub" << 'GRUBSPLASH'

# FurryOS Boot Splash
GRUB_BACKGROUND="/boot/grub/splash.png"
GRUB_TERMINAL_OUTPUT="gfxterm"
GRUB_GFXMODE=1920x1080,1024x768,800x600,auto
GRUB_GFXPAYLOAD_LINUX=keep
GRUBSPLASH

# Disable Plymouth in kernel parameters
sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT=.*/GRUB_CMDLINE_LINUX_DEFAULT="plymouth.enable=0"/' \
  "$SQUASHFS_ROOT/etc/default/grub"

# Remove Plymouth packages if present (no network needed)
chroot "$SQUASHFS_ROOT" /bin/bash -c "
  dpkg --purge plymouth plymouth-themes 2>/dev/null || true
" 2>&1 | grep -v "^$" || true

echo "  ✓ GRUB splash configured"
echo "  ✓ Plymouth disabled"

# ═══════════════════════════════════════════════════════════════════
# Phase 7: Mode Switching System
# ═══════════════════════════════════════════════════════════════════

echo ""
echo "[Phase 7] Installing Mode Switching System"

# Create mode switcher script
cat > "$SQUASHFS_ROOT/usr/local/bin/furryos-mode-switch" << 'MODESWITCHER'
#!/bin/bash
# FurryOS Mode Switcher - Gen2.1_v2

MODE="${1:-normal}"

case "$MODE" in
    granny)
        gsettings set org.mate.interface gtk-theme "HighContrast"
        gsettings set org.mate.interface icon-theme "HighContrast"
        gsettings set org.mate.interface font-name "Sans 14"
        gsettings set org.mate.Marco.general reduced-resources true
        ;;

    gamer)
        gsettings set org.mate.interface gtk-theme "BlackMATE"
        gsettings set org.mate.Marco.general compositing-manager false
        gsettings set org.mate.session idle-delay 0
        ;;

    hacker)
        gsettings set org.mate.interface gtk-theme "BlackMATE"
        gsettings set org.mate.terminal.profile:/org/mate/terminal/profiles/default/ use-theme-colors false
        gsettings set org.mate.terminal.profile:/org/mate/terminal/profiles/default/ background-color "#000000"
        gsettings set org.mate.terminal.profile:/org/mate/terminal/profiles/default/ foreground-color "#00FF00"
        ;;

    ghost)
        gsettings set org.mate.interface gtk-theme "Menta-Dark"
        gsettings set org.mate.interface icon-theme "Papirus-Dark"
        # Enable privacy features
        ;;

    normal|*)
        gsettings reset org.mate.interface gtk-theme
        gsettings reset org.mate.interface icon-theme
        ;;
esac

notify-send "FurryOS" "Switched to ${MODE^} Mode" -i preferences-desktop-theme 2>/dev/null || true
echo "✓ Mode: ${MODE^}"
MODESWITCHER

chmod +x "$SQUASHFS_ROOT/usr/local/bin/furryos-mode-switch"

# Create mode launcher desktop files
mkdir -p "$SQUASHFS_ROOT/usr/share/applications"

for mode in granny normal gamer hacker ghost; do
    cat > "$SQUASHFS_ROOT/usr/share/applications/furryos-mode-${mode}.desktop" << EOF
[Desktop Entry]
Version=1.0
Type=Application
Name=FurryOS ${mode^} Mode
Comment=Switch to ${mode^} mode
Exec=/usr/local/bin/furryos-mode-switch ${mode}
Icon=preferences-desktop-theme
Terminal=false
Categories=Settings;DesktopSettings;
EOF
done

echo "  ✓ Mode switching installed (5 modes)"

# ═══════════════════════════════════════════════════════════════════
# Phase 8: Live Boot Autostart
# ═══════════════════════════════════════════════════════════════════

echo ""
echo "[Phase 8] Configuring Live Boot Experience"
echo "..."

# Install live setup script if exists
SETUPSCRIPT="FurryOS_Live_Multimedia_Setup_Post_ISO_Gen2.1_v2.sh"
if [ -f "$PROJECT_ROOT/$SETUPSCRIPT" ]; then
  cp "$PROJECT_ROOT/$SETUPSCRIPT" "$SQUASHFS_ROOT/usr/local/bin/furryos-live-setup"
  chmod +x "$SQUASHFS_ROOT/usr/local/bin/furryos-live-setup"
  echo "  Live setup script installed"
fi

# Create autostart entry for live setup
mkdir -p "$SQUASHFS_ROOT/etc/skel/.config/autostart"
cat > "$SQUASHFS_ROOT/etc/skel/.config/autostart/furryos-live-setup.desktop" << 'AUTOSTART'
[Desktop Entry]
Type=Application
Name=FurryOS Live Setup
Exec=/usr/local/bin/furryos-live-setup
Terminal=false
Hidden=false
X-MATE-Autostart-enabled=true
AUTOSTART

# Copy desktop files to skeleton
if [ -d "$FURRYOS_SHARE/desktop" ]; then
  mkdir -p "$SQUASHFS_ROOT/etc/skel/Desktop"
  cp "$FURRYOS_SHARE/desktop"/*.desktop "$SQUASHFS_ROOT/etc/skel/Desktop/" 2>/dev/null || true
  chmod +x "$SQUASHFS_ROOT/etc/skel/Desktop"/*.desktop 2>/dev/null || true
  echo "  Desktop files configured"
fi

# Configure MATE desktop defaults with dconf
mkdir -p "$SQUASHFS_ROOT/etc/dconf/db/local.d"
cat > "$SQUASHFS_ROOT/etc/dconf/db/local.d/01-furryos" << 'DCONF'
[org/mate/desktop/background]
picture-filename='/usr/share/backgrounds/furryos/default.jpg'
picture-options='zoom'

[org/mate/sound]
event-sounds=true
theme-name='freedesktop'

[org/mate/session]
idle-delay=0
DCONF

# IMPORTANT: Create startup sound autostart entry
mkdir -p "$SQUASHFS_ROOT/etc/skel/.config/autostart"
cat > "$SQUASHFS_ROOT/etc/skel/.config/autostart/furryos-startup-sound.desktop" << 'STARTUPSOUND'
[Desktop Entry]
Type=Application
Name=FurryOS Startup Sound
Comment=Play FurryOS startup sound
Exec=/bin/bash -c "sleep 2 && paplay /usr/share/sounds/furryos/startup.ogg"
Terminal=false
Hidden=false
X-MATE-Autostart-enabled=true
X-MATE-Autostart-Delay=2
STARTUPSOUND

# Configure shutdown/logout sound
echo " Configuring shutdown sound..."

# Create shutdown sound script
cat > "$SQUASHFS_ROOT/usr/local/bin/furryos-shutdown-sound" << 'SHUTDOWNSCRIPT'
#!/bin/bash
SHUTDOWN_SOUND="/usr/share/sounds/furryos/shutdown.ogg"
if [ -f "$SHUTDOWN_SOUND" ]; then
  paplay "$SHUTDOWN_SOUND" 2>/dev/null || true
  sleep 1
fi
SHUTDOWNSCRIPT
chmod +x "$SQUASHFS_ROOT/usr/local/bin/furryos-shutdown-sound"

# Autostart helper that stays running and plays sound on session exit
mkdir -p "$SQUASHFS_ROOT/etc/skel/.config/autostart"
cat > "$SQUASHFS_ROOT/etc/skel/.config/autostart/furryos-shutdown-sound.desktop" << 'LOGOUTENTRY'
[Desktop Entry]
Type=Application
Name=FurryOS Shutdown Sound
Comment=Play sound on logout/shutdown
Exec=/bin/bash -c 'trap "/usr/local/bin/furryos-shutdown-sound" EXIT; sleep infinity'
Terminal=false
Hidden=true
X-MATE-Autostart-enabled=true
X-MATE-Autostart-Delay=0
NoDisplay=true
LOGOUTENTRY

echo " ✓ Shutdown sound configured"

# ═══════════════════════════════════════════════════════════════════
# Phase 8.5: Testing the Build on a VM before Packing Process
# ═══════════════════════════════════════════════════════════════════

echo ""
echo "Testing the unpacked filesystem is 3-10x faster than live boot or full ISO testing."
echo ""
echo "🚗 Give it a Test Drive before Packing for the ISO? [y/N]"
read -r TEST_DRIVE
if [[ $TEST_DRIVE =~ ^[Yy]$ ]]; then
    echo "🔧 Checking QEMU..."

    # Install QEMU + UEFI firmware if missing (one-liner)
    if ! command -v qemu-system-x86_64 >/dev/null 2>&1 || ! [ -d /usr/share/ovmf ]; then
        echo "📦 Installing QEMU + UEFI firmware..."
        sudo apt update -qq
        sudo apt install -y -qq qemu-system-x86 ovmf
        echo "✓ QEMU ready!"
    else
        echo "✓ QEMU already installed"
    fi

    # Quick unmount safety
    echo "🔄 Cleaning any old mounts..."
    for mp in "$SQUASHFS_ROOT"/{proc,sys,dev,run}; do
        sudo umount "$mp" 2>/dev/null || true
    done

    echo ""
    echo "🚀 Launching FurryOS Test VM (2GB RAM, KVM acceleration)"
    echo "• Wallpapers, sounds, modes, autostart will work exactly as in final ISO"
    echo "• Press Ctrl+C when done testing"
    echo ""

    sudo qemu-system-x86_64 \
        -kernel "$ISO_ROOT/live/vmlinuz" \
        -initrd "$ISO_ROOT/live/initrd.img" \
        -append "boot=live components quiet nosplash toram=filesystem.squashfs" \
        -drive file=fat:rw:"$SQUASHFS_ROOT",format=raw,if=virtio,id=drive0 \
        -device virtio-blk-pci,drive=drive0,bootindex=0 \
        -m 2048M -smp 2 -enable-kvm \
        -vga virtio -display gtk,gl=on,window-close=vm-shutdown \
        -usb -device usb-tablet \
        -rtc base=utc \
        -boot menu=on

    echo ""
    echo "✅ Test VM closed. Continuing to Phase 9 (SquashFS repack)..."
    echo ""

    # Pause so user sees the message
    sleep 2
fi

# Add this RIGHT AFTER Test Drive prompt (Phase 8.5), before Phase 9
echo ""
echo "🚀 Next: Pack ISO?"
echo "  [P]ack now      - Build final ISO immediately"
echo "  [K]eep unpacked - Chroot tweak → THEN pack ISO"
read -p "P/K [P]: " -n 1 -r NEXT_STEP
echo ""

if [[ ${NEXT_STEP,,} == "k" ]]; then
    echo "🔧 Entering unpacked filesystem (full Debian powers!)"
    echo "  • apt update && apt install ANYTHING"
    echo "  • Edit configs, test furryos-mode-switch gamer"
    echo "  • type 'exit' → auto-cleans → packs ISO"
    echo ""

    # Full chroot setup
    sudo mount --bind /dev "$SQUASHFS_ROOT/dev"
    sudo mount -t proc proc "$SQUASHFS_ROOT/proc"
    sudo mount --rbind /sys "$SQUASHFS_ROOT/sys"
    sudo mount --bind /run "$SQUASHFS_ROOT/run"

    sudo chroot "$SQUASHFS_ROOT" /bin/bash -i

    # Auto-clean mounts
    echo "🧹 Cleaning mounts..."
    sudo umount "$SQUASHFS_ROOT"/{dev,proc,sys,run} 2>/dev/null || true
    echo "✅ Unpacked filesystem ready → packing ISO now..."
fi

echo "[Phase 9] Repacking SquashFS..."  # Continue to your existing Phase 9

# ═══════════════════════════════════════════════════════════════════
# Phase 9-11: Repack & Finalize
# ═══════════════════════════════════════════════════════════════════

# Faster test compression (switch to LZ4 for dev)
if [[ $FAST_BUILD == "true" ]]; then
    COMP="-comp lz4 -b 1048576"
else
    COMP="-comp xz -b 1048576"
fi
sudo mksquashfs "$SQUASHFS_ROOT" "$ISO_ROOT/live/filesystem.squashfs" $COMP ...

echo ""
echo "[Phase 9] Repacking SquashFS"
rm -f "$ISO_ROOT/live/filesystem.squashfs"
echo "  Creating filesystem.squashfs (this takes time)..."
sudo mksquashfs "$SQUASHFS_ROOT" "$ISO_ROOT/live/filesystem.squashfs" \
    -comp xz \
    -b 1048576 \
    -mem "$SQUASHFS_MEM" \
    -processors "$SQUASHFS_CPUS" \
    -Xbcj x86 \
    -e boot \
    -noappend \
    >/dev/null
echo "  ✓ SquashFS repacked (${SQUASHFS_MEM} RAM, ${SQUASHFS_CPUS} CPUs)"

echo ""
echo "[Phase 10] Building Bootable ISO"
mkdir -p "$OUTPUT_DIR"
OUTPUT_ISO="$OUTPUT_DIR/furryos-gen2.1-amd64.iso"
rm -f "$OUTPUT_ISO"

sudo xorriso -as mkisofs \
    -iso-level 3 \
    -full-iso9660-filenames \
    -volid "FurryOS Gen2.1_v2" \
    -eltorito-boot isolinux/isolinux.bin \
    -eltorito-catalog isolinux/boot.cat \
    -no-emul-boot \
    -boot-load-size 4 \
    -boot-info-table \
    -isohybrid-mbr /usr/lib/ISOLINUX/isohdpfx.bin \
    -eltorito-alt-boot \
    -e boot/grub/efi.img \
    -no-emul-boot \
    -isohybrid-gpt-basdat \
    -output "$OUTPUT_ISO" \
    "$ISO_ROOT" 2>/dev/null

echo "  ✓ ISO created"

echo ""
echo "[Phase 11] Generating Checksums"
cd "$OUTPUT_DIR"
sha256sum "$(basename "$OUTPUT_ISO")" > "$(basename "$OUTPUT_ISO").sha256"

echo ""
echo "[Phase 12] Fixing Permissions"
sudo chown -R "$USER":"$USER" "$GENERATED"

# ═══════════════════════════════════════════════════════════════════
# Build Complete
# ═══════════════════════════════════════════════════════════════════

echo ""
echo "══════════════════════════════════════════════════════════════"
echo "             ✅ FurryOS Gen2.1_v2 Build Complete!"
echo "══════════════════════════════════════════════════════════════"
echo ""
echo "Output: $OUTPUT_ISO"
echo "Build directory: $BUILD_DIR"

SIZE=$(stat -c%s "$OUTPUT_ISO" 2>/dev/null || stat -f%z "$OUTPUT_ISO" 2>/dev/null)
echo "Size:   $(numfmt --to=iec-i --suffix=B $SIZE 2>/dev/null || echo "$SIZE bytes")"
echo "SHA256: $(cat "$(basename "$OUTPUT_ISO").sha256" | cut -d" " -f1)"
echo ""
echo "Features Included:"
echo "  ✓ GRUB boot splash with custom theme"
echo "  ✓ 5 mode profiles (Granny/Normal/Gamer/Hacker/Ghost)"
echo "  ✓ Mode-based software bundle system"
echo "  ✓ Automatic live boot setup"
echo "  ✓ ~/FurryOS folder creation"
echo "  ✓ Wallpaper and startup sound"
echo "  ✓ Desktop file deployment"
echo ""
echo "Test Command:"
echo "  qemu-system-x86_64 -cdrom $OUTPUT_ISO -m 2G -enable-kvm"
echo ""
echo "══════════════════════════════════════════════════════════════"

# Display total build time
BUILD_END_TIME=$(date +%s)
BUILD_DURATION=$((BUILD_END_TIME - BUILD_START_TIME))
BUILD_MINUTES=$((BUILD_DURATION / 60))
BUILD_SECONDS=$((BUILD_DURATION % 60))

echo ""
echo "═══════════════════════════════════════════════════════════════════"
echo "⏱️  Total build time: ${BUILD_MINUTES}m ${BUILD_SECONDS}s"
echo "═══════════════════════════════════════════════════════════════════"
